import 'package:flutter/material.dart';
import 'package:flutter_plugin_league_notice/src/helper/constants.dart';
import 'package:flutter_plugin_league_notice/src/helper/get_builder_ids.dart';
import 'package:flutter_plugin_league_notice/src/model/wait_done_news_data.dart';
import 'package:flutter_plugin_league_notice/src/model/wait_done_news_detail_data.dart';
import 'package:flutter_plugin_version/flutter_plugin_version.dart';

/// 元祖返回类型
typedef _AcrionResultRecod = ({bool success, String message});

class WaitDoneDetailListController extends GetxController with _WaitDoneDetailRequest {
  late final WaitDoneNewsModel _model;
  late final String _appCode; // 应用编码
  int? appType; // 应用类型

  // 当前加载的页数
  int _page = 1;
  // 列表底部空间距离
  EdgeInsets bottomEdgeInsets = const EdgeInsets.only(bottom: NoticeConstants.kPadding * 3);
  // 刷新控制器
  //EasyRefreshController refreshController = EasyRefreshController(controlFinishRefresh: true, controlFinishLoad: true);
  // 滚动控制器
  ScrollController scrollController = ScrollController();
  // 明细data
  WaitDoneNewsDetailData _detailData = WaitDoneNewsDetailData();
  // 明细列表
  List<WaitDoneNewsCategroyModel>? newsCategroies;

  // 是否可进行刷新
  bool loadMore = true;

  @override
  void onInit() {
    _model = Get.arguments as WaitDoneNewsModel;
    _appCode = _model.appCode ?? '';
    appType = _model.appType;

    super.onInit();
  }

  @override
  void onReady() {
    handlerOnRefresh(showLoading: true);
    super.onReady();
  }

  @override
  onClose() {
    _page = 1;
    // refreshController.dispose();
    scrollController.dispose();
    AiToastView.removeQueuedToasts();
    super.onClose();
  }

  /// 下拉刷新最新消息；上拉取历史消息
  Future<void> handlerOnRefresh({
    bool showLoading = false,
  }) async {
    // 请求此消息的明细列表
    if (_appCode.isNotEmpty) {
      newsCategroies ??= [];

      _detailData = await _requestWaitDoneMessageDetailList(
        _appCode,
        page: _page,
        showLoading: showLoading,
      );
      List<WaitDoneNewsCategroyModel> resultList = _detailData.list;

      if (_detailData.total < NoticeConstants.kLoadSize) {
        // 已经没有新数据
        loadMore = false;
      } else {
        _page++;
        loadMore = true;
      }

      newsCategroies!.addAll(resultList);
      // 结束下拉刷新
      // refreshController.finishLoad();
      // 进行列表刷新
      update([NoticeBuilderIds.id_wait_done_detail_list]);
    }
  }

  /// 点击进入应用
  void handlerEnterAppEvent() {}

  /// 点击跳转链接
  void handlerJumpLinkEvent(WaitDoneNewsCategroyModel currentNews) {
    Get.to(
      () => NormalWebViewPage(
        url: currentNews.linkMsgUrl ?? '',
        title: currentNews.msgTitle ?? '',
      ),
    );
  }

  /// 点击动作
  Future<void> handlerActionEvent(
    WaitDoneActionModel actionModel, {
    required WaitDoneNewsCategroyModel currentNews,
  }) async {
    // 请求action操作
    _AcrionResultRecod result = await _requestWaitDoneActionDispose(
      msgNo: actionModel.msgNo ?? '',
      actionCode: actionModel.actionCode ?? '',
    );

    if (result.success) {
      // 隐藏单签点击的动作组件,并更新UI
      currentNews.actionClickStatus = 1;
      update([NoticeBuilderIds.id_wait_done_detail_list_actions]);
    }
    AiToastView.showText(result.message);
  }
}

/// 请求
mixin _WaitDoneDetailRequest {
  ///
  /// 待办 消息列表明细列表
  ///
  Future<WaitDoneNewsDetailData> _requestWaitDoneMessageDetailList(
    String appCode, {
    int page = 1,
    bool showLoading = false,
  }) async {
    WaitDoneNewsDetailData data = WaitDoneNewsDetailData();

    if (showLoading) {
      AiToastView.showIndicator();
    }
    try {
      var model = await AppRequest.requestWaitDoneMsgDetailList(
        appCode,
        page: page,
        size: NoticeConstants.kLoadSize,
      );
      data = WaitDoneNewsDetailData.fromJson(model.data ?? {});
    } catch (e) {
      AiLog.e('获取待办消息列表明细列表异常：$e');
    } finally {
      if (showLoading) {
        AiToastView.removeToast();
      }
    }
    return data;
  }

  ///
  /// 待办 消息列表明细点击action，进行操作动作处理
  ///
  Future<_AcrionResultRecod> _requestWaitDoneActionDispose({
    required String msgNo,
    required String actionCode,
  }) async {
    _AcrionResultRecod result = (success: false, message: 'Fail');

    AiToastView.showIndicator();
    try {
      var model = await AppRequest.requestWaitDoneActionDispose(
        msgNo: msgNo,
        actionCode: actionCode,
      );
      result = (success: model.isSuccess, message: model.data ?? (model.isSuccess ? 'OK' : model.msg ?? 'Fail'));
    } catch (e) {
      AiLog.e('获取待办消息列表明细点击动作操作异常：$e');
    } finally {
      AiToastView.removeToast();
    }

    return result;
  }
}
